/**
 * coomix UI的公共脚本方法,弹大框（DOM、HTML、IFRAME、AJAX）
 * 具体使用说明请参见：webcontent/coomixDialogDemo.htm
 */
(function() {
	if (window.coomixDialog) return;
	var objType = function(type) {
		return new Function('o', "return Object.prototype.toString.call(o)=='[object " + type + "]'");
	}; 
	var isArray = objType('Array'),
	isObj = objType('Object'); 
	window.coomixDialog = {
		apply: function(o, c, d) {
			if (d) coomixDialog.apply(o, d);
			if (o && c && isObj(c)) for (var p in c) o[p] = c[p];
			return o;
		},
		eventList: []
	};
	var initFn = ['setDefaultCfg', 'show'], _initFn = {}, t;
	while (t = initFn.shift()) coomixDialog[t] = eval('0,function(){_initFn.' + t + '?_initFn.' + t + '.push(arguments):(_initFn.' + t + '=[arguments])}');
	var isIE = !+'\v1'; //IE浏览器
	var isCompat = document.compatMode == 'CSS1Compat';	
	var IE6 = isIE && /MSIE (\d)\./.test(navigator.userAgent) && parseInt(RegExp.$1) < 7; 
	var useFixed = !isIE || (!IE6 && isCompat); 
	var $ = function(id) {return document.getElementById(id);}; //获取元素
	var $height = function(obj) {return parseInt(obj.style.height) || obj.offsetHeight;}; //获取元素高度
	var addEvent = (function() {
		return new Function('env', 'fn', 'obj', 'obj=obj||document;' + (window.attachEvent ? "obj.attachEvent('on'+env,fn)": 'obj.addEventListener(env,fn,false)') + ';coomixDialog.eventList.push([env,fn,obj])');
	})();
	var detachEvent = (function() {
		return new Function('env', 'fn', 'obj', 'obj=obj||document;' + (window.attachEvent ? "obj.detachEvent('on'+env,fn)": 'obj.removeEventListener(env,fn,false)'));
	})();
	//设置样式
	var setStyle = function(el, n, v) {
		if (!el) return;
		if (isObj(n)) {
			for (var i in n) setStyle(el, i, n[i]);
			return;
		}
		if (isArray(el) || /htmlcollection|nodelist/i.test('' + el)) {
			for (var i = el.length - 1; i >= 0; i--) setStyle(el[i], n, v);
			return;
		}
		try {
			el.style[n] = v;
		} catch(e) {}
	};
	var btnIndex = 0, btnCache, seed = 0; 
	/*创建按钮*/
	var mkBtn = function(txt, sign, autoClose, id) {
		if (!txt) return;
		if (isArray(txt)) {
			var item, t = [],
			dftBtn = {
				OK: [curCfg.okTxt, 'ok'],
				CANCEL: [curCfg.cancelTxt, 'cancel']
			};
			while (txt.length)(item = txt.shift()) && t[t.push(mkBtn.apply(null, dftBtn[item] || item)) - 1] || t.pop();
			return t;
		}
		id = id || 'cmdialogPrompt_btn_' + seed++;
		autoClose = autoClose == undefined ? 'undefined': !!autoClose;
		return {
			id: id,
			html: "<input type='button' id='" + id + "' onclick='coomixDialog.doHandler(\"" + sign + "\"," + autoClose + ")' style='cursor:pointer' class='btnStyle handler' value='" + txt + "' />"
		};
	};
	/*生成按钮*/
	var joinBtn = function(btn) {
		if (!btn) return btnCache = '';
		if (!isArray(btn)) btn = [btn];
		if (!btn.length) return btnCache = '';
		btnCache = btn.concat();
		var html = [];
		while (btn.length) html.push(btn.shift().html);
		return html.join('&nbsp;&nbsp;');
	};
	/*默认配置*/
	var dftCfg = {
		message: '内容',		//消息框内容
		width: 300,				//消息框宽度
		height: 185,			//消息框高度
		title: '标题',			//消息框标题
		handler: function() {},	//回调事件
		maskAlphaColor: '#000',	//遮罩透明色，默认黑色
		maskAlpha: 0.1,			//遮罩透明度，默认0.1
		iframe: false,			//iframe模式，默认不是
		icoCls: '',				//消息框左侧图标，默认无
		btn: null,				//消息框显示的按钮，默认无
		autoClose: true,		//点击关闭、确定等按钮是否自动关闭，默认自动关闭
		fixPosition: true,		//是否随滚动条滚动，默认是
		dragOut: false,			//是否允许拖出窗口范围，默认不允许
		titleBar: true,			//是否显示标题栏，默认显示
		showMask: true,			//是否显示遮罩，默认显示
		winAlpha: 0.8,			//拖动时消息框的透明度，默认0.8
		closeBtn: true,			//是否显示关闭按钮，默认显示
		okTxt: '确 定',		//确定按钮的提示文本
		cancelTxt: '取 消'	//取消按钮的提示文本
	},curCfg = {};

	(function() {
		var rootEl = document.body, callee = arguments.callee;
		rootEl = isCompat ? document.documentElement: rootEl; 
		/*获取scrollLeft和scrollTop，在fixed定位时返回0，0*/
		var getScrollPos = function() {
			return curCfg.fixPosition && useFixed ? [0, 0] : [rootEl.scrollLeft, rootEl.scrollTop];
		};
		/*保存窗口定位信息，弹出窗口相对页面左上角的坐标信息*/
		var saveWinInfo = function() {
			var pos = getScrollPos();
			coomixDialog.apply(dragVar, {
				_offX: parseInt(cmdialog_win.style.left) - pos[0],
				_offY: parseInt(cmdialog_win.style.top) - pos[1]
			});
		};
		var maskStyle = 'position:absolute;top:0;left:0;display:none;text-align:center';
		var div = document.createElement('div');
		div.innerHTML = [
		/*遮罩*/
		"<div id='maskLevel' style=\'" + maskStyle + ';z-index:10000;\'></div>', IE6 ? ("<iframe id='maskIframe' src='javascript:false' style='" + maskStyle + ";z-index:9999;filter:alpha(opacity=0);opacity:0'></iframe>") : '',
		/*窗体*/
		"<div id='coomix-dialog' style='position:absolute;z-index:10001;display:none'>", 
		 IE6 ? "<iframe src='javascript:false' style='width:100%;height:100%;position:absolute;top:0;left:0;z-index:-1'></iframe>": '', 
		 "<div class='cmdialog-tl' id='cmdialog-tl'><div class='cmdialog-tr'><div class='cmdialog-tc' style='cursor:move;'>",
		 "<div class='cmdialog-header-text'></div>", 
		 "<div class='cmdialog_close' title='关闭'><strong>X</strong></div>", 
		 "</div></div></div>", 
		 "<div class='cmdialog-ml' id='cmdialog-ml'><div class='cmdialog-mr'><div class='cmdialog-mc'><div class='cmdialog-body' style='position:relative'></div></div></div></div>", 
		 "<div class='cmdialog-ml' id='cmdialog-btnl'><div class='cmdialog-mr'><div class='cmdialog-btn'></div></div></div>", 
		 "<div class='cmdialog-bl' id='cmdialog-bl'><div class='cmdialog-br'><div class='cmdialog-bc'></div></div></div>", 
		 "</div>"]
		 .join('');
		document.body.appendChild(div);
		/*mask、window*/
		var maskLevel = $('maskLevel');
		var cmdialog_win = $('coomix-dialog');
		/*header*/
		var cmdialog_headbox = $('cmdialog-tl');
		var cmdialog_head = cmdialog_headbox.firstChild.firstChild;//cmdialog-tc
		var cmdialog_hText = cmdialog_head.firstChild;//标题元素
		var cmdialog_close = cmdialog_hText.nextSibling; //右上角的关闭图标
		/*content*/
		var cmdialog_body = $('cmdialog-ml').firstChild.firstChild.firstChild;
		/*button*/
		var cmdialog_btn = $('cmdialog-btnl');
		var cmdialog_btnContent = cmdialog_btn.firstChild.firstChild;
		/*bottom*/
		var cmdialog_bottom = $('cmdialog-bl');
		var maskEl = [maskLevel]; //遮罩元素
		IE6 && maskEl.push($('maskIframe'));
		var dragVar = {};
		addEvent('click', function() {
				coomixDialog.doHandler('close');
			},cmdialog_close); //关闭
		/*getWinSize取得页面实际大小*/
		var getWinSize = function() {
			return [Math.max(rootEl.scrollWidth, rootEl.clientWidth), Math.max(rootEl.scrollHeight, rootEl.clientHeight)];
		};
		var winSize = getWinSize(); //保存当前页面的实际大小
		/*事件绑定部分*/
		var bindEl = cmdialog_head.setCapture && cmdialog_head; //绑定拖放事件的对象，只有Ie下bindEl有效
		/*窗体透明度控制*/
		var filterWin = function(v) {
			/*鼠标按下时取消窗体的透明度，IE标准模式下透明度为1则直接清除透明属性，防止iframe窗口不能拖动滚动条*/
			setStyle(cmdialog_win, v == 1 && isCompat ? {
				filter: '',
				opacity: ''
			}: {
				filter: 'Alpha(opacity=' + v * 100 + ')',
				opacity: v
			});
		};
		/*mousemove事件*/
		var mEvent = function(e) {
			var sLeft = dragVar.offX + e.clientX;
			var sTop = dragVar.offY + e.clientY;
			if (!curCfg.dragOut) { //页面可见区域内拖动
				var pos = getScrollPos(),
				sl = pos[0],
				st = pos[1];
				sLeft = Math.min(Math.max(sLeft, sl), rootEl.clientWidth - cmdialog_win.offsetWidth + sl);
				sTop = Math.min(Math.max(sTop, st), rootEl.clientHeight - cmdialog_win.offsetHeight + st);
			} else if (curCfg.showMask && '' + winSize != '' + getWinSize()) //及时调整遮罩大小
			resizeMask(true);
			setStyle(cmdialog_win, {
				left: sLeft + 'px',
				top: sTop + 'px'
			});
		};
		/*mouseup事件*/
		var uEvent = function() {
			filterWin(1);
			detachEvent("mousemove", mEvent, bindEl);
			detachEvent("mouseup", uEvent, bindEl);
			saveWinInfo(); //保存当前窗口的位置
			curCfg.iframe && setStyle(getPage().nextSibling, 'display', 'none');
			if(bindEl){
				detachEvent("losecapture", uEvent, bindEl);
				bindEl.releaseCapture();
			}
		};
		addEvent('mousedown',function(e) {
			if ((e.srcElement || e.target) == cmdialog_close) return false; //点击关闭按钮不进行启用拖动处理
			filterWin(curCfg.winAlpha); //鼠标按下时窗体的透明度
			/*鼠标与弹出框的左上角的位移差*/
			coomixDialog.apply(dragVar, {
				offX: parseInt(cmdialog_win.style.left) - e.clientX,
				offY: parseInt(cmdialog_win.style.top) - e.clientY
			});
			addEvent("mousemove", mEvent, bindEl);
			addEvent("mouseup", uEvent, bindEl);
			if (curCfg.iframe) {
				var cfg = {display:''};
				var pg = getPage();
				isCompat && IE6 && coomixDialog.apply(cfg, {
					width: pg.offsetWidth,
					height: pg.offsetHeight
				}); 
				setStyle(pg.nextSibling, cfg);
			}
			/*IE下窗口外部拖动*/
			if(bindEl){
				addEvent("losecapture", uEvent, bindEl);
				bindEl.setCapture();
			}
		},
		cmdialog_head);
		/*页面滚动弹出窗口滚动*/
		var scrollEvent = function() {
			setStyle(cmdialog_win, {
				left: dragVar._offX + rootEl.scrollLeft + 'px',
				top: dragVar._offY + rootEl.scrollTop + 'px'
			});
		};
		/*键盘监听*/
		var keydownEvent = function(e) {
			var keyCode = e.keyCode;
			if (keyCode == 27) destroy(); //esc键
			if (btnCache) {
				var l = btnCache.length, nofocus;
				/*tab键/左右方向键切换焦点*/
				document.activeElement && document.activeElement.id != btnCache[btnIndex].id && (nofocus = true);
				if (keyCode == 9 || keyCode == 39) nofocus && (btnIndex = -1),
				$(btnCache[++btnIndex == l ? (--btnIndex) : btnIndex].id).focus();
				if (keyCode == 37) nofocus && (btnIndex = l),
				$(btnCache[--btnIndex < 0 ? (++btnIndex) : btnIndex].id).focus();
				if (keyCode == 13) return true;
			}
			/*禁止F1-F12/ tab 回车*/
			return keyEvent(e, (keyCode > 110 && keyCode < 123) || keyCode == 9 || keyCode == 13);
		};
		/*监听键盘事件*/
		var keyEvent = function(e, d) {
			e = e || event;
			/*允许对表单项进行操作*/
			if (!d && /input|select|textarea/i.test((e.srcElement || e.target).tagName)) return true;
			try {
				e.returnValue = false;
				e.keyCode = 0;
			} catch(ex) {
				e.preventDefault && e.preventDefault();
			}
			return false;
		};
		maskLevel.oncontextmenu = function(){
			return false;
		}; 
		/*重新计算遮罩的大小*/
		var resizeMask = function(noDelay) {
			setStyle(maskEl, 'display', 'none'); //先隐藏
			var size = getWinSize();
			var resize = function() {
				setStyle(maskEl, {
					width: size[0] + 'px',
					height: size[1] + 'px',
					display: ''
				});
			};
			isIE ? noDelay === true ? resize() : setTimeout(resize, 0) : resize();			
		};
		/*蒙版的显示隐藏,state:true显示,false隐藏，默认为true*/
		var maskVisible = function(visible) {
			if (!curCfg.showMask) return; //无遮罩
			(visible === false ? detachEvent: addEvent)("resize", resizeMask, window); //页面大小改变及时调整遮罩大小
			if (visible === false) return setStyle(maskEl, 'display', 'none'); //隐藏遮罩
			setStyle(maskLevel, {
				background: curCfg.maskAlphaColor,
				filter: 'Alpha(opacity=' + curCfg.maskAlpha * 100 + ')',
				opacity: curCfg.maskAlpha
			});
			resizeMask(true);
		};
		/*计算指定位置的坐标，返回数组*/
		var getPos = function() {
			var pos = [rootEl.clientWidth - cmdialog_win.offsetWidth, rootEl.clientHeight - cmdialog_win.offsetHeight].concat(getScrollPos());
			var arr = [];
			//居中显示
			arr[0] = pos[0]/2 + pos[2];
			arr[1] = pos[1]/2 + pos[3];
			return arr;
		}; 
		/*设定窗口大小及定位*/
		var setWinSize = function(w, h, pos) {
			if (cmdialog_win.style.display == 'none') return; //当前不可见则不处理
			/*默认使用配置的宽高*/
			h = parseInt(h) || curCfg.height;
			w = parseInt(w) || curCfg.width;
			setStyle(cmdialog_win, {
				width: w + 'px',
				height: h + 'px',
				left: 0,
				top: 0
			});
			pos = getPos();
			setStyle(cmdialog_win, {
				left: pos[0] + 'px',
				top: pos[1] + 'px'
			});
			saveWinInfo(); //保存当前窗口位置信息
			setStyle(cmdialog_body, 'height', h - $height(cmdialog_headbox) - $height(cmdialog_btn) - $height(cmdialog_bottom) + 'px'); //设定内容区的高度
			isCompat && IE6 && curCfg.iframe && setStyle(getPage(), {height: cmdialog_body.clientHeight}); //IE6标准模式下要计算iframe高度
		};
		var _obj = []; //IE中可见的obj元素
		var cacheWin = []; //队列中的窗口
		var winVisible = function(visible) {
			var fn = visible === false ? detachEvent: addEvent;
			fn('scroll', curCfg.fixPosition && !useFixed ? scrollEvent: saveWinInfo, window);
			setStyle(cmdialog_win, 'position', curCfg.fixPosition && useFixed ? 'fixed': 'absolute');
			fn('keydown', keydownEvent);
			if (visible === false) { //关闭
				var closeFn = function() {
					setStyle(cmdialog_win, 'display', 'none');
					setStyle(_obj, 'visibility', 'visible');
					_obj = []; 
					cacheWin.shift();
					if (cacheWin.length) coomixDialog.show.apply(null, cacheWin[0].concat(true));
				};
				closeFn();
				return;
			}
			for (var o = document.getElementsByTagName('object'), i = o.length - 1; i > -1; i--) {
				o[i].style.visibility != 'hidden' && _obj.push(o[i]) && (o[i].style.visibility = 'hidden');
			}
			setStyle([cmdialog_hText, cmdialog_close], 'display', (curCfg.titleBar ? '': 'none'));
			cmdialog_head.className = 'cmdialog-tc' + (curCfg.titleBar ? '': ' cmdialog-ttc'); //无标题栏
			cmdialog_hText.innerHTML = curCfg.title; //标题
			cmdialog_close.style.display = curCfg['closeBtn'] ? '': 'none';
			cmdialog_close.title = '关闭';
			var ifmStyle = 'position:absolute;width:100%;height:100%;top:0;left:0;opacity:1;filter:alpha(opacity=100)';
			//内容
			if(curCfg.iframe){
				if(isIE){
					cmdialog_body.innerHTML = "<iframe name='_coomixDialogIframe_' id='_coomixDialogIframe_' src='javascript:void(0)' style='" + ifmStyle + "' border='0' frameborder='0'></iframe><div style='" + ifmStyle + ";background:#000;opacity:0.1;filter:alpha(opacity=10);display:none'></div>";
					var load = function(){document.getElementById("_coomixDialogIframe_").src = curCfg.message;};
					setTimeout(load,10);
				}else{
					cmdialog_body.innerHTML = "<iframe src='" + curCfg.message + "' style='" + ifmStyle + "' border='0' frameborder='0'></iframe><div style='" + ifmStyle + ";background:#000;opacity:0.1;filter:alpha(opacity=10);display:none'></div>";
				}
			}else{
				cmdialog_body.innerHTML = '<div class="cmdialog-content">' + curCfg.message + '</div>';
			}
			cmdialog_body.className = "cmdialog-body " + curCfg.icoCls; //图标类型
			setStyle(cmdialog_btn, 'display', ((cmdialog_btnContent.innerHTML = joinBtn(mkBtn(curCfg.btn))) ? '': 'none'));
			setStyle(cmdialog_win, 'display', '');
			setWinSize();
			filterWin(1);
			btnCache && $(btnCache[btnIndex = 0].id).focus();
		}; 
		var init = function() {
			maskVisible();
			winVisible();
		}; //销毁
		var destroy = function() { 
			maskVisible(false);
			winVisible(false);
		}; 
		var getPage = function() {
			return curCfg.iframe ? cmdialog_body.firstChild: null;
		};
		coomixDialog.apply(coomixDialog, {
			close: destroy,
			getPage: getPage,
			/*显示消息框*/
			show: function(args, fargs, show) {
				if (!show && cacheWin.push([args, fargs]) && cacheWin.length > 1) return;
				var a = [].slice.call(args, 0), o = {}, j = -1;
				if (!isObj(a[0])) {
					for (var i in dftCfg) if (a[++j]) o[i] = a[j];
				} else {
					o = a[0];
				}
				coomixDialog.apply(curCfg, coomixDialog.apply({}, o, fargs), coomixDialog.setDefaultCfg());
				for (var i in curCfg) curCfg[i] = curCfg[i] != null ? curCfg[i] : coomixDialog.cfg[i];
				init();
			},
			doHandler: function(sign, autoClose, closeFirst) {
				if (autoClose == undefined ? curCfg.autoClose: autoClose) {
					destroy();
				}
				try { 
					(curCfg.handler)(sign);
				} catch(e) {
					alert(e.message);
				};
			},
			resizeWin: setWinSize,
			setDefaultCfg: function(cfg) {
				return coomixDialog.cfg = coomixDialog.apply({}, cfg, coomixDialog.apply({}, coomixDialog.cfg, dftCfg));
			},
			getButtons: function() {
				var btns = btnCache || [], btn, rBtn = [];
				while (btn = btns.shift()) rBtn.push($(btn.id));
				return rBtn;
			}
		});
		coomixDialog.setDefaultCfg(); 
		var t;
		for (var i in _initFn) while (t = _initFn[i].shift()) coomixDialog[i].apply(null, t);
		/*取消事件绑定*/
		addEvent('unload', function() {
			while (coomixDialog.eventList.length) detachEvent.apply(null, coomixDialog.eventList.shift());
		}, window);
	})();
})(); 
coomixDialog.apply(coomixDialog, {
	alert: function() {
		coomixDialog.show(arguments, {
			icoCls: 'cmdialog_alert',
			btn: ['OK']
		});
	},
	succeedInfo: function() {
		coomixDialog.show(arguments, {
			icoCls: 'cmdialog_succeed',
			btn: ['OK']
		});
	},
	error: function() {
		coomixDialog.show(arguments, {
			icoCls: 'cmdialog_error',
			btn: ['OK']
		});
	},
	confirm: function() {
		coomixDialog.show(arguments, {
			icoCls: 'cmdialog_confirm',
			btn: ['OK', 'CANCEL']
		});
	},
	win: function() {
		coomixDialog.show(arguments);
	}
});